package com.jt.deepSeaMain;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jt.controller.DeepSeaHttpController;
import com.jt.dto.CollectParamsDto;
import com.jt.pojo.Result;
import com.jt.pojo.Timing;
import com.jt.utils.HttpPostAndGetUtil;
import com.jt.utils.OkhttpUtil;
import com.jt.utils.RedisUtils;
import com.mysql.cj.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.*;

@Slf4j
@Component
public class HttpURLConnectionGetResult {
    @Autowired
    private HttpPostAndGetUtil httpPostAndGetUtil;

    @Autowired
    private OkhttpUtil okhttpUtil;

    @Autowired
    private RedisUtils redisUtils;

    @Value("${http.token.type}")
    private String tokenType;


    @Value("${http.token.url}")
    private String tokenUrl;

    @Value("${http.token.tokenDefalt}")
    private String tokenDefalt;

    @Value("${http.token.username}")
    private String username;

    @Value("${http.token.password}")
    private String password;

    /*获取深海token*/
    public Result getToken() {
        //        String userName = mapBady.get("userName").toString();
//        String password = mapBady.get("password").toString();
        String res = "";
        try {
//            String pathUrl = "http://51.25.255.88:32096/ifaas-authority/oauth/token";
//            Map<String, Object> map = new HashMap<>();
//            //固定token
//            String token = "Basic c3VwZXJ1c2VyOjEyMzQ1Ng==";
//            map.put("token", token);
//            String userName = "xjgaadmin";
//            map.put("username", userName);
////            password = Sha256Util.getSHA256StrJava(userName) + MD5Util.getEncryptedPwd(password);
//            String password="b24331b1a138cde62aa1f679164fc62f";
//            map.put("password", password);
//            //表单参数，授权模式，固定值
//            String grant_type = "password";
//            map.put("grant_type", grant_type);
//            //权限范围
//            String scope = "read write";
//            map.put("scope", scope);
//            res = httpPostAndGetUtil.postFormData(pathUrl, map, null, token);
//            System.out.println("输出结果==="+res);
            String pathUrl = "http://51.25.255.88:32096/ifaas-authority/oauth/token";
            String token = "Basic c3VwZXJ1c2VyOjEyMzQ1Ng==";
            String username = "xjgaadmin";
//            String password = "53e85fb396587353fba0e1d0ba5f5e6b";
            String password = "53e85fb396587353fba0e1d0ba5f5e6b";
            OkHttpClient client = new OkHttpClient().newBuilder().build();
            MediaType mediaType = MediaType.parse("text/plain");
            MultipartBody body = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("username", username).addFormDataPart("password", password)
                    .addFormDataPart("scope", "read write").addFormDataPart("grant_type", "password").build();
            Request request = new Request.Builder().url(pathUrl).method("POST", body).addHeader("token", token)
                    .build();
            Response response = client.newCall(request).execute();
            System.out.println("response结果====" + response);
            res = response.body().string();

//            System.out.println("结果====" + res);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result().setCode(200).setData(res).setMassage("获取token成功");

    }


    public String getCollectList(CollectParamsDto collectParamsDto) {
        String pathUrl = "http://127.0.0.1:32096/deep/collectList";
        String result = "";
        try {
            /*获取token，调用公共方法*/
            String token = tokenPublicVoid();
            log.info(">>>>获取token成功,值为{}",token);
            /*封装json*/
            Map<String, Object> params = new HashMap<>();
            params.put("sourceId", collectParamsDto.getSourceId());
            params.put("page", collectParamsDto.getPage());
            params.put("pageSize", collectParamsDto.getPageSize());
            params.put("access_token", token);
            if (!StringUtils.isNullOrEmpty(collectParamsDto.getTargetType())) {
                params.put("targetType", collectParamsDto.getTargetType());
            }
            if (!StringUtils.isNullOrEmpty(collectParamsDto.getRelative())) {
                params.put("relative", collectParamsDto.getRelative());
            }
            /*params.put("relative","body" )*/
            List<String> timeList = collectParamsDto.getTimeList();
            String arr[] = timeList.toArray(new String[timeList.size()]);
            /*时间格式数组 String arr[] = {"2024-04-10 12:30:33","2024-05-13 12:30:30"};*/
            params.put("db_insert_time", arr);
            JSONObject jsonObjectData = new JSONObject();
            String jsonData = jsonObjectData.toJSONString(params);
            String postResult = httpPostAndGetUtil.postJson(pathUrl, jsonData, "POST", null);
            if (StringUtils.isNullOrEmpty(postResult)) {
                result = "";
                return result;
            }
            result = postResult;
        } catch (Exception e) {
            log.error("getCollectList接口调用深海数据异常,异常为:{}", e.toString());
            e.printStackTrace();
        }
        return result;
    }

    /*公共从redis中获取token方法。深海每个接口都需要调用这个 ，获取DeepToken的值*/
    public String tokenPublicVoid() {

        Result result = getToken();
        String str = result.getData().toString();
        JSONObject jsonObject = JSON.parseObject(str);
        String  token = jsonObject.get("access_token").toString();

//        String token = "";
//        String expires_in = "";
//        try {
//            long deepTokenLong = redisUtils.getExpire("access_token");
//            token = redisUtils.get("access_token").toString();
//            if (deepTokenLong == -2 || deepTokenLong == -1) {
////              Result result = deepSeaHttpController.getNodeToken();
//                Result result = getToken();
////                Result result = getNodeToken();
//                String str = result.getData().toString();
//                JSONObject jsonObject = JSON.parseObject(str);
//                token = jsonObject.get("access_token").toString();
//                expires_in = jsonObject.get("expires_in").toString();
//                redisUtils.set("access_token",token, Long.valueOf(expires_in));
//            } else {
//                token = redisUtils.get("access_token").toString();
//            }
//        } catch (Exception e) {
//            log.error("getToken接口调用获取token异常,异常为:{}", e.toString());
//            e.printStackTrace();
//        }
        return token;
    }

    public Result getNodeToken() throws IOException {
        String token = "";
        String pathUrl = "http://127.0.0.1:32096/deep/token";
        try {
            String result = okhttpUtil.post(pathUrl, null, null);
////            System.out.println("获取接口返回的的token结果值==="+tokenRes);
//            String result = httpPostAndGetUtil.postJson(pathUrl, null, "POST", null);
            System.out.println("获取token接口返回的result的结果值===" + result);
            JSONObject jsonObject = JSON.parseObject(result);
            String access_token = jsonObject.get("access_token").toString();
            System.out.println("获取接口返回access_token===" + access_token);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result().setCode(200).setData(token);
    }

}
